package org.linlinjava.litemall.wx.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.constant.ReturnValue;
import org.linlinjava.litemall.core.mapper.SysPlatformCutpriceHistoryMap;
import org.linlinjava.litemall.db.domain.LitemallRedPacaketsHistory;
import org.linlinjava.litemall.db.po.LookCutpricePo;
import org.linlinjava.litemall.db.po.UserListPo;
import org.linlinjava.litemall.wx.po.GiveRedPacaketsPo;
import org.linlinjava.litemall.wx.service.WxRedPacaketsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wx/redpacakets")
@Validated
@Api(value = "盘红包API", tags = "盘红包API", description = "盘红包")
public class WxRedPacaketsController {
    private final Log logger = LogFactory.getLog(WxRedPacaketsController.class);

    @Autowired
    private WxRedPacaketsService wxRedPacaketsService;

    @PostMapping(path = "/enterprisePayment")
    @ApiOperation(value = " 企业付款到微信零钱")
    public ResponseEntity<?> enterprisePayment(@RequestBody GiveRedPacaketsPo givePo) {
        return  wxRedPacaketsService.enterprisePayment(givePo.getUserItemListId(), givePo.getAppletName(), givePo.getOpenId());
    }

    @PostMapping(path = "/generateQr")
    @ApiOperation(value = "生成二维码")
    @ResponseBody
    public ResponseEntity<?> generateQr(@RequestBody GiveRedPacaketsPo qrPo ) throws Exception {
        return wxRedPacaketsService.generateQr(qrPo.getUserItemListId(),qrPo.getAppletName());
    }
    /**
     * 红包列表
     *
     * @return 订单列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取红包列表服务")
    public Object list() {
        return wxRedPacaketsService.list(10);
    }

    @PostMapping(path = "/giveRedPacaket")
    @ApiOperation(value = "用户领取红包")
    public ResponseEntity<?> giveCoupon(@RequestBody GiveRedPacaketsPo givePo) {
        try {
            int flag = wxRedPacaketsService.giveCoupon(givePo.getUserItemListId(), givePo.getAppletName());
            if (flag == 1) {
                return new ResponseEntity<>(new ReturnValue(ReturnValue.success, "success"), HttpStatus.OK);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.error("不满足条件");
        return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, "不可领取"), HttpStatus.OK);
    }


    /**
     * 砍价活动 用户查询自己发出的砍价活动
     *
     * @param userId
     * @return
     * @Auther: wangly
     * @Date: 2019/5/30 0030 上午 9:20
     */
    @GetMapping(path = "/findCutpriceByUserId")
    @ApiOperation(value = "查询平台券的已完成或进行中的砍价活动")
    public ResponseEntity<?> findCutpriceByUserId(@RequestParam String userId) {

        logger.info("WechatAppletController++++++++++findCutpriceByUserId 用户查询自己发出的已完成或进行中的砍价活动" + ",userId:" + userId);
        try {
            if (StringUtils.isBlank(userId)) {
                return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, "参数为空"), HttpStatus.OK);
            }


            List<LookCutpricePo> byUserIdAndStoreId = null;
            byUserIdAndStoreId = wxRedPacaketsService.findCutpriceByUserIdNew(userId);


            List<UserListPo> receivedUserList = wxRedPacaketsService.receivedUserList();
            if (byUserIdAndStoreId != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("LookCutpricePos", byUserIdAndStoreId);
                map.put("ReceivedUserList", receivedUserList);
                return new ResponseEntity<>(new ReturnValue(ReturnValue.success, map), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(new ReturnValue(ReturnValue.success, null), HttpStatus.OK);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<Object>(new ReturnValue(ReturnValue.fail, null), HttpStatus.OK);
    }


    @GetMapping(path = "/getCutRedPacakets")
    @ApiOperation(value = "活动id获取已经发起的盘红包活动详情")
    public ResponseEntity<?> getCutRedPacakets(String cutredpacaketId, String userOpenId) {
        try {
            LookCutpricePo lookCutpricePo = wxRedPacaketsService.getCutredPacaketsById(Long.parseLong(cutredpacaketId), userOpenId);
            if (lookCutpricePo != null) {
                return new ResponseEntity<>(new ReturnValue(ReturnValue.success, lookCutpricePo), HttpStatus.OK);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new ResponseEntity<Object>(new ReturnValue(ReturnValue.fail, "活动失效"), HttpStatus.OK);
    }

    @PostMapping(path = "/platformCutpriceBargain")
    @ApiOperation(value = "发起平台代金券砍价活动")
    public ResponseEntity<?> platformCutpriceBargain(@RequestBody SysPlatformCutpriceHistoryMap platformCutpriceHistory,
                                                     String formId) {
        //logger.info("PlatformCutpriceBargain++++++++++userId:" + platformCutpriceHistory.getWopenId() + ",cutId:" + platformCutpriceHistory.getCutpriceId());
        if (platformCutpriceHistory.getWopenId() == null || platformCutpriceHistory.getCutpriceId() == null) {
            logger.error("发起盘红包活动，参数为空");
            return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, "参数为空"), HttpStatus.OK);
        }
        try {
            LitemallRedPacaketsHistory sfch = wxRedPacaketsService.platformCutpriceBargain(platformCutpriceHistory, formId);
            //  List<UserListPo> receivedUserList = wxRedPacaketsService.receivedUserList();

            if (sfch != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("sfch", sfch);
                //   map.put("ReceivedUserList", receivedUserList);
                return new ResponseEntity<>(new ReturnValue(ReturnValue.success, map), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(new ReturnValue(ReturnValue.success, "平台代金券不可用或竞拍券已发起"), HttpStatus.OK);
            }
        } catch (Exception e) {
            // e.printStackTrace();
            logger.error(e.getMessage(), e);
            return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, "网络错误"), HttpStatus.OK);
        }
    }

    /**
     * 平台代金券亲友帮砍
     * <p>Description: </p>
     *
     * @return
     * @throws Exception
     * @author caiy
     * @date 2019年6月5日
     */
    @PostMapping(path = "/friendsBargainPlatformCutprice")
    @ApiOperation(value = "亲友帮砍")
    public ResponseEntity<?> friendsBargainPlatformCutprice(@RequestBody GiveRedPacaketsPo cutPacketPo, String formId) throws Exception {
        if (StringUtils.isBlank(cutPacketPo.getOpenId()) || cutPacketPo.getUserItemListId() == null) {
            return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, "参数错误"), HttpStatus.OK);
        }
        int cutprice = wxRedPacaketsService.friendsBargainPlatformCutprice(cutPacketPo.getOpenId(), cutPacketPo.getUserItemListId(), formId,cutPacketPo.getAppletName());
        if (cutprice >= 1) {
            return new ResponseEntity<>(new ReturnValue(ReturnValue.success, cutprice), HttpStatus.OK);
        } else {
            String message = wxRedPacaketsService.getMessage();
            if (StringUtils.isNotBlank(message)) {
                wxRedPacaketsService.setMessage(null);
                return new ResponseEntity<>(new ReturnValue(ReturnValue.fail, message), HttpStatus.OK);
            }
            return new ResponseEntity<Object>(new ReturnValue(ReturnValue.fail, "活动失效"), HttpStatus.OK);
        }
    }


}
